//根据返回的类型判断是跳转到本程序页面还是 h5链接
function pagebyTypeJump(type, url, pageId) {
	// 链接类型:site=网页,miniapp=小程序
	if (url) {
		if (type == 'site') {
			uni.navigateTo({
				url: '/pages/webView?pageurl=' + encodeURIComponent(url)
			})
		}
		if (type == 'miniapp') {
			uni.navigateTo({
				url: url
			})
		}
	}
	// console.log('测试', type, url)
}

function isValidPhoneNumber(phoneNumber) {
	const regex = /^1[3-9]\d{9}$/;
	return regex.test(phoneNumber);
}

function filedownload(file) {
	uni.showLoading({
		title: '下载中'
	});
	let that = this
	uni.downloadFile({
		url: file, //这里配置下载的路径
		success: (data) => {
			if (data.statusCode === 200) {
				const fileManager = uni.getFileSystemManager();
				fileManager.saveFile({ //文件保存到本地
					tempFilePath: data.tempFilePath, //临时路径
					success: function(res) {
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件已保存!',
							duration: 3000,
						});
						uni.openDocument({
							fileType: 'pdf',
							filePath: res.savedFilePath,
							showMenu: true,
							success: function(res) {}
						});
						uni.hideLoading()
					}
				});
			}
		}
	});
}
// 企业微信客服
function openEnterpriseKF(file) {
	// #ifdef  MP-WEIXIN  
	wx.openCustomerServiceChat({
		extInfo: {
			url: 'https://work.weixin.qq.com/kfid/kfc6c8447b2e4daec3d' //客服地址链接
		},
		corpId: 'ww632540a0ddff1564', //必须和你小程序上的一致
		success(res) {
			console.log(res, '企业微信客服')
		},
		fail(res) {
			console.log(res, '企业微信客服')
		},
	})
	// #endif
}
// 根据subjectcateId跳转到不同的页面查看结果
function diffResultById(subjectcateId, recordId,type ) {
	if (!type) {
		if (subjectcateId == 3) {
			uni.navigateTo({
				url: '/pages/onlineTest/lookResultInfo?record_id=' + recordId + '&jumpTag=in'
			});
		}
		if (subjectcateId == 1) {
			uni.navigateTo({
				url: '/pages/onlineTest/lookResultInfoDetail?record_id=' + recordId + '&jumpTag=in'
			});
		}
		if (subjectcateId == 5) {
			uni.navigateTo({
				url: '/pages/onlineTest/lookResultInfoother?record_id=' + recordId + '&jumpTag=in'
			});
		}
	} else {
		if (subjectcateId == 3) {
			uni.navigateTo({
				url: '/pages/onlineTest/lookResultInfo?record_id=' + recordId + '&jumpTag=in' + '&pageType=tj'
			});
		}
		if (subjectcateId == 1) {
			uni.navigateTo({
				url: '/pages/onlineTest/lookResultInfoDetail?record_id=' + recordId + '&jumpTag=in' +
					'&pageType=tj'
			});
		}
		if (subjectcateId == 5) {
			uni.navigateTo({
				url: '/pages/onlineTest/lookResultInfoother?record_id=' + recordId + '&jumpTag=in' +
					'&pageType=tj'
			});
		}
	}
}
//截取uirl的路径和参数
function extractUrlParts(url, defaultPath = 'pages/onlineTest/onlinelist') {
	// 找到哈希符号(#)的位置  
	const hashIndex = url.indexOf('#');
	// 截取哈希符号之后的内容  
	let hashContent = hashIndex !== -1 ? url.substring(hashIndex + 1) : '';
	// 如果哈希内容为空，则返回默认值  
	if (!hashContent) {
		return {
			path: defaultPath,
			params: {}
		};
	}
	// 分割路径和查询参数（如果存在）  
	const pathAndQueryParams = hashContent.split('?');
	const path = pathAndQueryParams[0];
	const queryParams = pathAndQueryParams[1] ? parseQueryParams(pathAndQueryParams[1]) : {};
	return {
		path,
		params: queryParams
	};
}

function parseQueryParams(queryString) {
	const params = {};
	const pairs = queryString.split('&');
	pairs.forEach(pair => {
		const [key, value] = pair.split('=');
		params[decodeURIComponent(key)] = decodeURIComponent(value);
	});
	return params;
}
// 截取url中的code方法
function getUrlCode() {
	let url = location.href
	// 创建一个URL对象  
	const urlObj = new URL(url);
	// 使用URLSearchParams API获取查询参数  
	const params = new URLSearchParams(urlObj.search);
	// 尝试获取指定参数的值，如果不存在则返回null  
	const paramValue = params.get('code');
	uni.setStorageSync('wxCode', paramValue ? paramValue : '')
	return paramValue ? paramValue : ''; // 如果存在则返回值，否则返回空字符串 
}
// 工作号授权登录
function wechatLogin() {
	const _this = this
	const appId = 'wx089c8d48d16b8bd1' // 你的微信公众号appid
	uni.setStorageSync('hrefPath', extractUrlParts(location.href).path)
	uni.setStorageSync('hrefQyery', JSON.stringify(extractUrlParts(location.href).params))
	if (process.env.VUE_APP_PLATFORM === 'h5') {
		var ua = navigator.userAgent.toLowerCase();
		if (ua.match(/MicroMessenger/i) == "micromessenger") {
			let appid = appId
			let scope = "snsapi_base"
			let url =
				`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(window.location.origin + "/wap/#" + (extractUrlParts(location.href).path|| 'pages/onlineTest/onlinelist'))}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`
			// 唤起链接,如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE
			window.location.href = url
		} else {
			uni.showToast({
				icon: 'none',
				position: 'bottom',
				title: '请在微信客户端打开'
			});
		}
	}
}
import ajax from '@/static/js/ajax' // 路径需根据项目实际情况
function publiclogin() {
	if (uni.getStorageSync('token')) return
	// 走登录
	ajax.get('/user/login', {
		code: uni.getStorageSync('wxCode')
	}).then((res) => {
		if (res.code == 1) {
			uni.setStorageSync('token', res.data.userinfo.token);
			uni.setStorageSync('userinfo', res.data.userinfo);
			uni.setStorageSync('wxlogininfo', res.data.wxinfo);
		}
	});
}

function startLogin(pagePath) {
	getUrlCode()
	let wxCode = uni.getStorageSync('wxCode')
	if (!wxCode) {
		wechatLogin()
	} else {
		publiclogin()
	}
	if (pagePath) {
		uni.setStorageSync("index-path", pagePath)
	} else {
		uni.setStorageSync("index-path", '')
	}
}
const uaTag = navigator.userAgent.toLowerCase().match(/micromessenger/i) == 'micromessenger'
export {
	pagebyTypeJump,
	isValidPhoneNumber,
	filedownload,
	openEnterpriseKF,
	diffResultById,
	getUrlCode,
	wechatLogin,
	publiclogin,
	startLogin,
	uaTag
}